package org.peoples.users {
	
	import com.qualityattributes.collections.ICollection;
	import com.qualityattributes.collections.maps.HashMap;
	import com.qualityattributes.errors.UnsupportedOperationError;
	import com.qualityattributes.lang.QInteger;
	
	import flash.events.EventDispatcher;
	
	public class UserPool extends EventDispatcher {
		
		private var users:HashMap;
		private static var instance:UserPool;
		private static var instanceCheck:int = 0;
		
		public function UserPool():void {
			if (instanceCheck == 0)
				throw new UnsupportedOperationError("UserPool must be instantiated by using UserPool.getInstance()");
				
			users = new HashMap();
		}
		
		public function addUser(user:User):Boolean {
			if (!users.containsValue(user)) {
				users.putItem(new QInteger(user.ID), user);
				
				var evt:UserPoolEvent = new UserPoolEvent(UserPoolEvent.USER_ADDED, user);
				dispatchEvent(evt);
				
				return true;
			}
			
			return false;
		}
		
		public function getAllUsers():ICollection {
			return users.values();
		}
		
		public static function getInstance():UserPool {
			instanceCheck = 1;
			if (instance == null)
				instance = new UserPool();
				
			return instance;
		}
		
		public function getUser(id:int):User {
			return users.getItem(new QInteger(id)) as User;
		}
		
		public function removeUser(id:int):User {
			var user:User = users.remove(new QInteger(id)) as User;
			
			if (user != null) {
				var evt:UserPoolEvent = new UserPoolEvent(UserPoolEvent.USER_REMOVED, user);
				dispatchEvent(evt);
			}
			
			return user;
		}
		
	}
	
}